package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/cache"
	_ "github.com/astaxie/beego/cache/redis"
	"github.com/astaxie/beego/orm"
	"goweb/models"
	"time"
)

type AreaController struct {
	beego.Controller
}

func (this *AreaController) RetData(resp map[string]interface{}) {
	this.Data["json"] = resp
	this.ServeJSON()
}

func (c *AreaController) GetArea() {
	resp := make(map[string]interface{})
	resp["errno"] = 0
	resp["errmsg"] = "ok"
	defer c.RetData(resp)

	//从缓存中取
	redis_cnn, err := cache.NewCache("redis", `{"key":"goweb","conn":"127.0.0.1:6379","dbNum":"1"}`)
	areainfo := redis_cnn.Get("areas")

	if areainfo != nil {
		var areaData interface{}
		json.Unmarshal(areainfo.([]byte), &areaData)
		resp["data"] = &areaData
		return
	}
	//从数据库拿数据
	var areas []models.Area
	o := orm.NewOrm()
	num, err := o.QueryTable("area").All(&areas)
	if err != nil {
		resp["errno"] = 4001
		resp["errmsg"] = "查询失败"
		return
	}
	if num == 0 {
		resp["errno"] = 4002
		resp["errmsg"] = "没有查询到相关数据"
		return
	}
	fmt.Println("areas:", areas)
	resp["data"] = areas
	//把数据写入redis
	json_str, err := json.Marshal(areas)
	if err != nil {
		fmt.Println("encoding err")
		return
	}
	fmt.Println("json_str=", json_str)
	errinfo := redis_cnn.Put("areas", json_str, time.Second*60)
	if errinfo != nil {
		fmt.Println("redis写入错误")
	}
}
